/*
 * @Author: boboan 360969885@qq.com
 * @Date: 2022-07-22 00:52:22
 * @LastEditors: boboan 360969885@qq.com
 * @LastEditTime: 2022-07-29 19:06:00
 * @FilePath: /react-vite-template/src/pages/p-cnpc/services/request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import config from "../config";
import LoadingStack from "@/utils/LoadingStack";
import { store } from "../redux/store";
import _ from "lodash";
import Toast from "@/components/Toast";
import ErrorHandler from './ErrorHandler'

const baseURL = config.APP_SMARTLINK_API;

const instance = axios.create({
  baseURL: baseURL,
  // timeout: 60000
});

// 请求拦截
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    // 是否应该携带token？
    const token = store.getState().app.token;

    config.headers.token = token;
    config.headers.product = "faw";

    // 临时的 
    _.merge(config.data || {}, {
      userId: store.getState().app.uinfo.ucId
    });

    LoadingStack.whenRequest(config);

    return config;
  },
  function (error) {
    // 对请求错误做些什么
    LoadingStack.whenResponse(error?.config);
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    console.log(response)
    LoadingStack.whenResponse(response?.config);

    if (response.data && response.data.resultCode && response.data.resultCode !== 200) {
      // resultCode为code值的后台。这里判断一下code值
      ErrorHandler(response.data)
    }
    if (response.data && response.data.code && response.data.code !== 200) {
      // code为code值的后台。这里判断一下code值
      ErrorHandler(response.data)
    }
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    LoadingStack.whenResponse(error?.config);

    // http code值的错误处理
    ErrorHandler(error.response)

    // 提示网络开小差了
    if (!error?.response && error?.message === 'Network Error') {
      Toast.info('网络开小差了，稍后再试吧！')
    }
    return Promise.reject(error);
  }
);

export default instance;
